import com.iheartradio.m3u8.*;
import com.iheartradio.m3u8.data.MediaPlaylist;
import com.iheartradio.m3u8.data.Playlist;
import com.iheartradio.m3u8.data.TrackData;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author NingWang
 * 2020-01-08 21:26
 */
public class M3U8Parser {
    private static final HttpClient httpClient = HttpClient.getInstance();

    static public List<String> parseWithUrl(String url){
        String m3u8Str = httpClient.downloadM3U8(url);
        System.out.println(m3u8Str);
        try{
            InputStream inputStream = new ByteArrayInputStream(m3u8Str.getBytes());
            PlaylistParser parser = new PlaylistParser(inputStream, Format.EXT_M3U, Encoding.UTF_8);
            String urlPrefix =  url.substring(0, url.lastIndexOf("/")+1);
            List<String> result = new ArrayList<String>();
            Playlist playlist = parser.parse();
            if (playlist.hasMediaPlaylist()){
                MediaPlaylist mediaPlaylist = playlist.getMediaPlaylist();
                List<TrackData> trackDatas = mediaPlaylist.getTracks();
                for(TrackData data:trackDatas){
                    result.add(urlPrefix + data.getUri());
                }
                return result;
            }
            return null;
        }catch (Exception e){
            return null;
        }
    }

    static public List<String> parseWithFile(String baseUrl,  String filePath) throws IOException{
        File file = new File(filePath);

        InputStream inputStream = new FileInputStream(file);
        PlaylistParser parser = new PlaylistParser(inputStream, Format.EXT_M3U, Encoding.UTF_8);
        try{
            String urlPrefix =  baseUrl.substring(0, baseUrl.lastIndexOf("/")+1);
            List<String> result = new ArrayList<String>();
            Playlist playlist = parser.parse();
            if (playlist.hasMediaPlaylist()){
                MediaPlaylist mediaPlaylist = playlist.getMediaPlaylist();
                List<TrackData> trackDatas = mediaPlaylist.getTracks();
                for(TrackData data:trackDatas){
                    result.add(urlPrefix + data.getUri());
                }
                return result;
            }
            return null;
        }catch (Exception ignore){
            return null;
        }

    }

    public static void main(String[] args) throws Exception {
        List<String> result =  parseWithUrl("https://video1.yocoolnet.in/files/mp4/I/E/s/IEsTP.m3u8");
        if(result!=null){
            result.forEach(System.out::println);
        }

    }


}
